package com.bupt.utils;

import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component
public class RedisCommonProcessor {
 
    @Autowired
    private RedisTemplate redisTemplate;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public Object get(String key) {
        if(key == null) {
            throw new UnsupportedOperationException("Redis key could not be null!");
        }
        return stringRedisTemplate.opsForValue().get(key);
    }
 
    public void set(String key, Object value) {
        String jsonStr = JSONUtil.toJsonStr(value);
        stringRedisTemplate.opsForValue().set(JSONUtil.toJsonStr(key), jsonStr);
    }
 
    public void set(String key, Object value, long time) {
        if (time > 0) {
            String jsonStr = JSONUtil.toJsonStr(value);
            stringRedisTemplate.opsForValue().set(key, jsonStr, time, TimeUnit.SECONDS);
        } else {
            set(key, value);
        }
    }

    public void remove(String key) {
        stringRedisTemplate.delete(key);
    }

}